package com.dtsz.m2;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.activity.LoginActivity;
import com.dtsz.m2.ui.activity.MedalWallActivity;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.HomeVo;
import com.dtsz.m2.ui.model.MwRecordVo;
import com.dtsz.m2.utils.PackageUtils;
import com.dtsz.m2.utils.StatusBarUtils;
import com.dtsz.m2.utils.UpdateManager;
import com.dtsz.m2.volley.state.HUCState;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.lang.reflect.Field;

import cn.jpush.android.api.JPushInterface;


public class MainActivity extends BaseActivity {
    private UpdateManager updateManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final String token = pageVo.getToken();
        if ("token001".equals(token)) {
            sendIntent(this, LoginActivity.class);
            finish();
        } else {
            //写入共享缓存
            setContentView(R.layout.activity_main);
            StatusBarUtils.setTransparentStatusBar(this);
            BottomNavigationView navView = findViewById(R.id.nav_view);
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
            disableShiftMode(navView);
            NavigationUI.setupWithNavController(navView, navController);
        }
        updateManager = new UpdateManager(this);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请READ_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    HUCState.HUC_REQEUST_CODE_1);
        } else {
            getVersion();
            getNot();
        }

        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(this);
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId("947070428")
                //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                .setExpressViewAcceptedSize(500,500)
                .setSupportDeepLink(true)
                .setOrientation(TTAdConstant.VERTICAL)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .setAdLoadType(TTAdLoadType.PRELOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build();




        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                ttFullScreenVideoAd.showFullScreenVideoAd(MainActivity.this, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);

            }

            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {

            }
        });




    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @SuppressLint("RestrictedApi")
    public static void disableShiftMode(BottomNavigationView view) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("labelVisibilityMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setInt(menuView, 1);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                item.setShifting(false);
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "Unable to get shift mode field", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "Unable to change value of shift mode", e);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    private void getVersion() {
        //获取网络数据
        pageVo.setLikeName("钱包");
        pageVo.setClientId(JPushInterface.getRegistrationID(getApplicationContext()));
        hucRequestInterfase.executeStr(this, HomeVo.class,
                HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.VERSION_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void getNot() {
        hucRequestInterfase.executeStr(this, HomeVo.class, 100, Request.Method.GET, UrlConfig.NOT_URL, hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public void onErrorLogin(int inputType) {
        super.onErrorLogin(inputType);
        sendIntent(this, LoginActivity.class);
    }
    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_5:
                if (response instanceof HomeVo) {
                    HomeVo homeVo = (HomeVo) response;
                    String version = homeVo.getContent();
                    String usersionC = PackageUtils.getAppVersionName(this);
                    String[] strings = version.split(",");
                    if (!usersionC.equals(strings[0]) && strings.length > 1) {
                        getBindPhone(homeVo.getState(), strings[0], homeVo.getTitle(), strings[1]);
                    } else {
                        String isMedal = homeVo.getIsMedal();
                        if ("1".equals(isMedal)) {
                            setMealdlAlert(homeVo);
                        }
                    }
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                String re = (String) response;
                if ("成功".equals(re)) {
                    alertDialog1.dismiss();
                    sendIntent(this, MedalWallActivity.class);
                } else {
                    showToast(re);
                }
                break;
            case 100:
                sendUrl(UrlConfig.NOT_URL);
                break;
        }
        loadDismiss();
    }

    AlertDialog alertDialog1;

    @SuppressLint("SetTextI18n")
    private void getBindPhone(String state, String usersionC, String content, String url) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(this).inflate(R.layout.item_version, null);
        ProgressBar progressBar = root.findViewById(R.id.pb_o);
        TextView versionRoot = root.findViewById(R.id.tv_version);
        TextView tvContent = root.findViewById(R.id.tv_content);
        tvContent.setText(content);
        versionRoot.setText("V" + usersionC);

        int roundRadius = 15; // 8dp 圆角半径 The x-radius of the oval used to round the corners

        //准备progressBar带圆角的背景Drawable
        GradientDrawable progressBg = new GradientDrawable();
        //设置圆角弧度
        progressBg.setCornerRadius(roundRadius);
        //设置绘制颜色
        progressBg.setColor(getResources().getColor(R.color.colorFont));


        //准备progressBar带圆角的进度条Drawable
        GradientDrawable progressContent = new GradientDrawable();
        progressContent.setCornerRadius(roundRadius);
        //设置绘制颜色，此处可以自己获取不同的颜色
        progressContent.setColor(getResources().getColor(R.color.colorFont13));

        //ClipDrawable是对一个Drawable进行剪切操作，可以控制这个drawable的剪切区域，以及相相对于容器的对齐方式
        ClipDrawable progressClip = new ClipDrawable(progressContent, Gravity.LEFT, ClipDrawable.HORIZONTAL);
        //Setup LayerDrawable and assign to progressBar
        //待设置的Drawable数组
        Drawable[] progressDrawables = {progressBg, progressClip};
        LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);
        //根据ID设置progressBar对应内容的Drawable
        progressLayerDrawable.setId(0, android.R.id.background);
        progressLayerDrawable.setId(1, android.R.id.progress);
        //设置progressBarDrawable
        progressBar.setProgressDrawable(progressLayerDrawable);

        if ("1".equals(state)) {//强制更新
            root.findViewById(R.id.tv_cancel).setVisibility(View.GONE);
        }
        dialog.setView(root);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateManager.showDownloadDialog(progressBar, alertDialog1, url);
            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        try {
            alertDialog1.show();
        } catch (Exception e) {

        }
    }

    private void setMealdlAlert(HomeVo homeVo) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(this).inflate(R.layout.popupwindow_mealdl_alert, null);
        ImageView tvImage = root.findViewById(R.id.tv_image);
        Glide.with(this).load(homeVo.getLightUrl()).into(tvImage);
        TextView tvName = root.findViewById(R.id.tv_name);
        tvName.setText(homeVo.getName());
        TextView tvNum = root.findViewById(R.id.tv_num);
        tvNum.setVisibility(View.GONE);
        tvNum.setText(homeVo.getReward());
        dialog.setView(root);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MwRecordVo mwRecordVo = new MwRecordVo();
                mwRecordVo.setToken(pageVo.getToken());
                mwRecordVo.setLanguage("1");
                mwRecordVo.setGrade(homeVo.getGrade());
                mwRecordVo.setType(homeVo.getType());
                updateStatus(mwRecordVo);
            }
        });
        root.findViewById(R.id.tv_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    void updateStatus(MwRecordVo mwRecordVo) {
        loading();
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.UPDATESTATUS_URL,
                hucParameInterfase.getRequestParameter(mwRecordVo), false);
    }


//    private ShowInterstitialADListener getShowInterstitialADListener() {
//        return new ShowInterstitialADListener() {
//
//            @Override
//            public void onADReceive() {
//                Log.i(TAG, "onADReceive");
//            }
//
//            @Override
//            public void onVideoCached() {
//                Log.i(TAG, "onVideoCached");
//            }
//
//            @Override
//            public void onVideoComplete() {
//                Log.i(TAG, "onVideoComplete");
//            }
//
//            @Override
//            public void onVideoStart() {
//                Log.i(TAG, "onVideoStart");
//            }
//
//            @Override
//            public void onNoAD(int errorCode) {
//                Log.i(TAG, "onNoAD errorCode" + errorCode);
//            }
//
//            @Override
//            public void onADOpened() {
//                Log.i(TAG, "onADOpened");
//            }
//
//            @Override
//            public void onADExposure() {
//                Log.i(TAG, "onADExposure");
//            }
//
//            @Override
//            public void onADClicked() {
//                Log.i(TAG, "onADClicked");
//            }
//
//            @Override
//            public void onADClosed() {
//                Log.i(TAG, "onADClosed");
//            }
//        };
//    }

}
